<template>
    <div class="wrapper">
			<!-- header部分 -->
			<header>
				<div class="icon-location-box">
					<div class="icon-location"></div>
				</div>
				<div class="location-text">
					<i class="fas fa-map-marker-alt" ></i>
					{{ this.address }}
					<i class="fa fa-caret-down" @click="toTestLocation"></i>
				</div>
			</header>

				<!--app为整个组件的根元素-->
				<div ref="status"></div>
				<div ref="result"></div>
				<div ref="map"></div>
				<!-- <input type="text" id="address" readonly class="address-input"> -->

			<!-- search部分 -->
			<!-- 搜索框部分（此块与search-fixed-top块宽度高度一致，用于当search-fixed-top块固定后，挡住下面块不要窜上去）-->
			<div class="search">
				<!-- 当滚动条超过上面的定位块时，search-fixed-top块变成固定在顶部。 -->
				<div class="search-fixed-top" ref="fixedBox" @click="toLocationSearch">
					<!-- 搜索框部分中间的白框 -->
					<div class="search-box">
						<i class="fa fa-search"></i>搜索饿了么商家、商品名称
					</div>
				</div>
			</div>

			<!-- 点餐分类部分 -->
			<ul class="foodtype">
				<li @click="toBusinessList(1)">
					<img src="../assets/dcfl01.png">
					<p>美食</p>
				</li>
				<li @click="toBusinessList(2)">
					<img src="../assets/dcfl02.png">
					<p>早餐</p>
				</li>
				<li @click="toBusinessList(3)">
					<img src="../assets/dcfl03.png">
					<p>跑腿代购</p>
				</li>
				<li @click="toBusinessList(4)">
					<img src="../assets/dcfl04.png">
					<p>汉堡披萨</p>
				</li>
				<li @click="toBusinessList(5)">
					<img src="../assets/dcfl05.png">
					<p>甜品饮品</p>
				</li>
				<li @click="toBusinessList(6)">
					<img src="../assets/dcfl06.png">
					<p>速食简餐</p>
				</li>
				<li @click="toBusinessList(7)">
					<img src="../assets/dcfl07.png">
					<p>地方小吃</p>
				</li>
				<li @click="toBusinessList(8)">
					<img src="../assets/dcfl08.png">
					<p>米粉面馆</p>
				</li>
				<li @click="toBusinessList(9)">
					<img src="../assets/dcfl09.png">
					<p>包子粥铺</p>
				</li>
				<li @click="toBusinessList(10)">
					<img src="../assets/dcfl10.png">
					<p>炸鸡炸串</p>
				</li>
			</ul>
			<!-- 横幅广告部分 -->
			<div class="banner">
				<!-- 小标题用h标题 -->
				<h3>品质套餐</h3>
				<p>搭配齐全吃得好</p>
				<!-- 转义字符“<” -->
				<a>立即抢购 &gt;</a>
			</div>
			<!-- 超级会员部分 -->
			<div class="supermember">
				<div class="left">
					<img src='../assets/super_member.png'>
					<h3>超级会员</h3>
					<!-- 转义字符 -->
					<p>&#8226; 每月享超值权益</p>
				</div>
				<!-- <div class="right"> -->
				<div class="right" @click="toPayDone">
					<!--转义字符 -->
					立即开通 &gt;
				</div>
			</div>
			<!-- 推荐商家部分 -->
			<div class="recommend">
				<div class="recommend-line"></div>
				<p>推荐商家</p>
				<div class="recommend-line"></div>
			</div>
			<!-- 推荐方式部分 -->
			<ul class="recommendtype">
				<li>综合排序<i class="fa fa-caret-down"></i></li>
				<li>距离最近</li>
				<li>销量最高</li>
				<li>筛选<i class="fa fa-filter"></i></li>
			</ul>
			<!-- 推荐商家列表部分 -->
			<ul class="business">
				<li v-for="item in businessArr" :key="item.id">
					<img :src="item.businessImg" @click="toBusinessInfo(item.businessId)">
					<div class="business-info">
						<div class="business-info-h">
							<h3>{{item.businessName}}</h3>
							<!-- 方框内白色点 -->
							<div class="business-info-like">&#8226;</div>
						</div>
						<!-- 星级评价部分 -->
						<div class="business-info-star">
							<!-- 左边五颗星等级 -->
							<div class="business-info-star-left">
								<i class="fa fa-star"></i>
								<i class="fa fa-star"></i>
								<i class="fa fa-star"></i>
								<i class="fa fa-star"></i>
								<i class="fa fa-star"></i>
								<!-- 评价结果等级 -->
								<p>4.9 月售345单</p>
							</div>
							<!-- 星级评价右边部分 -->
							<div class="business-info-star-right">
								蜂鸟专送
							</div>
						</div>
						<div class="business-info-delivery">
							<p>&#165;{{item.starPrice}}起送 | &#165;{{item.deliveryPrice}}配送</p>
							<p>3.22km | 30分钟</p>
						</div>
						<div class="business-info-explain">
							<div>{{item.businessExplain}}</div>
						</div>
						<div class="business-info-promotion">
							<div class="business-info-promotion-left">
								<div class="business-info-promotion-left-incon">新</div>
								<p>饿了么新用户首单立减9元</p>
							</div>
							<div class="business-info-promotion-right">
								<p>2个活动</p>
								<i class="fa fa-caret-down"></i>
							</div>
						</div>
						<div class="business-info-promotion">
							<div class="business-info-promotion-left">
								<div class="business-info-promotion-left-incon" style="background-color: #F1884F;">特</div>
								<p>特价商品5元起</p>
							</div>
						</div>
					</div>
				</li>
			</ul>
			<!-- 底部菜单部分 -->
			<footer-page />
		</div>
</template>

<script>
import FooterPage from '../components/FooterPage.vue'
import AMapLoader from '@amap/amap-jsapi-loader';

export default{
    name:'IndexPage',
    // mounted 钩子函数 会在组件挂载到 DOM 后被调用 
    // DOM 是 Document Object Model（文档对象模型）的缩写
    // 不用created()函数，created() 钩子函数在组件实例创建后立即调用
    data(){
		return{
			businessArr:[],
			user:{},
			address:'',
			lng:'',
			lat:''
      }
	},
	mounted(){
        /*
        *1.使用哪一个事件
        * 使用onscroll，移动端和pc端都有效
        * 2.获取滚动条位置
        * 获取pc端的滚动条位置：document.documentElement.scrollTop
        * 移动端：document.body.scrollTop
        * 3如何获取视口宽度
        * document.documentElement.clientWidth(都有效)
        */
        // 获取滚动条位置
        //若是仍然使用function，会导致fixedBox那块的this到document来，不是到对象，要使用等号箭头
        document.onscroll = () => {
            let s1 = document.documentElement.scrollTop;
            let s2 = document.body.scrollTop;
            let scroll = s1===0?s2:s1;
            // 获取视口宽度
            let width = document.documentElement.clientWidth;
            // 获取顶部固定块，改成用vue的格式，在前面将id改成ref
            // 使用 ref 属性标记 DOM 元素，可以更方便地在 Vue 组件中获取和操作这些元素
            // 而无需使用传统的 id 和 getElementById
            // let search = document.getElementById('fixedBox');
            let search = this.$refs.fixedBox;
            if(scroll>width*0.12){
                search.style.position = 'fixed';
                search.style.left = '0';
                search.style.top = '0';
            }else{
                search.style.position = 'static';
            }
        }
		// this.initMap();
		window._AMapSecurityConfig = {
				securityJsCode: 'a06b202f0e99d85437d0a5e778eb6bcb'
			};

		AMapLoader.load({
			key: '771416183bdd6f18d141c0d35d65014d',
			version: '2.0',
			plugins: ['AMap.CitySearch', 'AMap.Geolocation', 'AMap.Geocoder']
		}).then((AMap) => {
			AMap.plugin('AMap.Geolocation', () => {
			const geolocation = new AMap.Geolocation({
				enableHighAccuracy: true,
				timeout: 10000,
				position: 'RB',
				offset: [10, 20],
				zoomToAccuracy: true
			});
			const mapContainer = this.$refs.map; // 获取地图容器的引用
			const statusContainer = this.$refs.status; // 获取状态容器的引用
			const resultContainer = this.$refs.result; // 获取结果容器的引用
			
			const map = new AMap.Map(mapContainer); // 初始化地图
			map.addControl(geolocation);
			geolocation.getCurrentPosition((status, result) => {
				if (status === 'complete') {
				//this.onComplete(result, statusContainer, resultContainer); // 将状态容器和结果容器作为参数传递
					console.log('定位成功');
				// 将经纬度转换为地址
					AMap.plugin('AMap.Geocoder', () => {
					const geocoder = new AMap.Geocoder({
						city: "010", // 城市设为北京，默认：“全国”
						radius: 500// 范围，默认：500
					});

					const lnglat = [result.position.lng, result.position.lat]; // 获取经纬度信息
					this.lng = result.position.lng;
					this.lat = result.position.lat;

					var self = this;

					geocoder.getAddress(lnglat, function(status, result) {
						console.log('将经纬度转换为地址'+status, result);
						if (status === 'complete' && result.regeocode) {
						const address = result.regeocode.formattedAddress;
						// document.getElementById('address').value = address; // 将地址信息显示在输入框中
						// const jsonAddress = JSON.stringify(address);
						self.address = address;
						// sessionStorage.setItem('jsonAddress', jsonAddress); // 将地址信息存储到sessionStorage的"address"键下
						} else {
						console.error('根据经纬度查询地址失败');
						}
					});
					});
				} else {
				this.onError(result, statusContainer, resultContainer); // 将状态容器和结果容器作为参数传递
				}
			});
			});
		}).catch((error) => {
			this.onError(error, this.$refs.status, this.$refs.result); // 将状态容器和结果容器作为参数传递
		});
        
    },
	created() {
		this.user = this.$getSessionStorage('user');

		// this.address = this.$getSessionStorage('address');

		let url = `/BusinessController/listBusinessByOrderTypeId/1`;
		this.$axios.get(url)
		.then(response =>{ 
			console.log(response.data.result)
			this.businessArr = response.data.result;
		})
		.catch(error => {
			console.error(error);//调用 console.error() 方法，用于将错误信息输出到控制台
		});
	},
	unmounted() {
        //当切换到其他组件时，就不需要document滚动条事件，所以将此事件去掉
		// console.log(this.destroyed);
        document.onscroll = null;
    }
    ,components: {
        FooterPage
    }
    ,methods:{
        toBusinessList(orderTypeId){
			console.log(this.$route.path);
            this.$router.push({path:'/businessList', query:{orderTypeId:orderTypeId}});
        },
		toBusinessInfo(businessId){
			this.$router.push({path:'/businessInfo',query:{businessId:businessId}});
		},
		toPayDone(){
			//首先做登录判断
            if(this.user === null){
                this.$router.push({
                    path : '/login'
                });
                return ;
            }
				this.$axios.post(`UserController/getMember/${this.user.token.token}`, this.$qs.stringify({
					//userId:this.user.userId,
					period: 30
				}))
				.then(response =>{
					if(response.data !== null || response.data !== ''){
						alert('开通会员成功！');
						this.$router.push({path:'/payDone',query:{orderTotal: 9.9,  isMember: true}});
					}
					else{
						alert('开通会员失败，请重试！')
					}		

				})
				.catch(error => {
					console.error(error);
				});
		},
		toTestLocation(){
			this.$router.push({path:'/testLocation', query:{lng: this.lng, lat:this.lat}});
		},
		toLocationSearch(){
			this.$router.push({path:'/locationSearch'});
		},
		//initMap() {
		// 	window._AMapSecurityConfig = {
		// 		securityJsCode: 'a06b202f0e99d85437d0a5e778eb6bcb'
		// 	};

		// AMapLoader.load({
		// 	key: '771416183bdd6f18d141c0d35d65014d',
		// 	version: '2.0',
		// 	plugins: ['AMap.CitySearch', 'AMap.Geolocation', 'AMap.Geocoder']
		// }).then((AMap) => {
		// 	AMap.plugin('AMap.Geolocation', () => {
		// 	const geolocation = new AMap.Geolocation({
		// 		enableHighAccuracy: true,
		// 		timeout: 10000,
		// 		position: 'RB',
		// 		offset: [10, 20],
		// 		zoomToAccuracy: true
		// 	});
		// 	const mapContainer = this.$refs.map; // 获取地图容器的引用
		// 	const statusContainer = this.$refs.status; // 获取状态容器的引用
		// 	const resultContainer = this.$refs.result; // 获取结果容器的引用
			
		// 	const map = new AMap.Map(mapContainer); // 初始化地图
		// 	map.addControl(geolocation);
		// 	geolocation.getCurrentPosition((status, result) => {
		// 		if (status === 'complete') {
		// 		//this.onComplete(result, statusContainer, resultContainer); // 将状态容器和结果容器作为参数传递
		// 			console.log('定位成功');
		// 		// 将经纬度转换为地址
		// 			AMap.plugin('AMap.Geocoder', () => {
		// 			const geocoder = new AMap.Geocoder({
		// 				city: "010", // 城市设为北京，默认：“全国”
		// 				radius: 500// 范围，默认：500
		// 			});

		// 			const lnglat = [result.position.lng, result.position.lat]; // 获取经纬度信息

		// 			geocoder.getAddress(lnglat, function(status, result) {
		// 				console.log('将经纬度转换为地址'+status, result);
		// 				if (status === 'complete' && result.regeocode) {
		// 				const address = result.regeocode.formattedAddress;
		// 				// document.getElementById('address').value = address; // 将地址信息显示在输入框中
		// 				const jsonAddress = JSON.stringify(address);
		// 				this.jsonAddress = jsonAddress;
		// 				// sessionStorage.setItem('jsonAddress', jsonAddress); // 将地址信息存储到sessionStorage的"address"键下
		// 				} else {
		// 				console.error('根据经纬度查询地址失败');
		// 				}
		// 			});
		// 			});
		// 		} else {
		// 		this.onError(result, statusContainer, resultContainer); // 将状态容器和结果容器作为参数传递
		// 		}
		// 	});
		// 	});
		// }).catch((error) => {
		// 	this.onError(error, this.$refs.status, this.$refs.result); // 将状态容器和结果容器作为参数传递
		// });
		//},
		//onComplete(data, statusContainer, resultContainer) {
		// statusContainer.innerHTML = '定位成功';
		// const str = [];
		// str.push('定位结果：' + data.position);
		// str.push('定位类别：' + data.location_type);
		// if (data.accuracy) {
		// 	str.push('精度：' + data.accuracy + ' 米');
		// }
		// str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'));
		// resultContainer.innerHTML = str.join('<br>');
		// },
		// onError(data, statusContainer, resultContainer) {
		// statusContainer.innerHTML = '定位失败';
		// resultContainer.innerHTML =
		// 	'失败原因排查信息:' + data.message + '</br>浏览器返回信息：' + data.originMessage;
		// 
		// }
		
    }

}
</script>

<style scoped>
    /***************** 总容器 ******************/
.wrapper {
	width: 100%;
	height: 100%;
}

/****************** header ******************/
.wrapper header {
	width: 100%;
	/*视口宽度的12%*/
	height: 12vw;
	background-color: #0097FF;
	/* 弹性布局
  垂直方向居中*/
	display: flex;
	align-items: center;
}

.wrapper header .icon-location-box {
	width: 3.5vw;
	height: 3.5vw;
	/* 上下左右外边距 */
	margin: 0 1vw 0 3vw;
}

/* 头部字体颜色 */
.wrapper header .location-text {
	font-size: 4.5vw;
	font-weight: 700;
	color: #fff;
}

/* 定位符号与地址不相靠 */
.wrapper header .location-text .fa-caret-down {
	/* 设置左外边距 */
	margin-left: 1vw;
}


/****************** search ******************/
.wrapper .search {
	width: 100%;
	height: 13vw;
}

.wrapper .search .search-fixed-top {
	width: 100%;
	height: 13vw;
	background-color: #0097FF;
	display: flex;
	justify-content: center;
	align-items: center;
}

.wrapper .search .search-fixed-top .search-box {
	/* 搜索框大小 */
	width: 90%;
	height: 9vw;
	background-color: #fff;
	border-radius: 2px;
	/* 弹性布局居中 */
	display: flex;
	justify-content: center;
	align-items: center;
	/* 字体大小颜色 */
	font-size: 3.5vw;
	color: #AEAEAE;
	font-family: "宋体";
	/*此样式是让文本选中状态无效*/
	user-select: none;
}

/* 搜索图标和文字保持距离 */
.wrapper .search .search-fixed-top .search-box .fa-search {
	margin-right: 1vw;
}

/****************** 点餐分类部分 ******************/
.wrapper .foodtype {
	width: 100%;
	height: 48vw;

	display: flex;
	flex-wrap: wrap;
	/* 两边不紧靠边框 */
	justify-content: space-around;
	/*要使用align-content。10个子元素将自动换行为两行，而且两行作为一个整体垂直居中*/
	/* 两行作为整体居中 */
	align-content: center;
}

/* 一行五张图片，分为两行 */
.wrapper .foodtype li {
	/*一共10个子元素，通过计算，子元素宽度在16.7 ~ 20 之间，才能保证换两行*/
	width: 18vw;
	height: 20vw;

	display: flex;
	/*弹性盒子主轴方向设为column，然后仍然是垂直水平方向居中*/
	flex-direction: column;
	justify-content: center;
	align-items: center;
	/* 设置文字不被选中 */
	user-select: none;
	cursor: pointer;
}

.wrapper .foodtype li img {
	width: 12vw;
	/*视频讲解时高度设置为12vw，实际上设置为10.3vw更佳*/
	height: 10.3vw;
}

/* 改变字体大小 */
.wrapper .foodtype li p {
	font-size: 3.2vw;
	color: #666;
}

/****************** 横幅广告部分 ******************/
.wrapper .banner {
	/**
 * 设置容器宽度95%，然后水平居中，这样两边留白; 
 * 这里不能用padding，因为背景图片也会覆盖padding
 */
	width: 95%;
	margin: 0 auto;
	height: 29vw;

	/*此三个样式组合，可以保证背景图片充满整个容器*/
	/* 让整个图片自适应整个容器 */
	background-image: url(../assets/index_banner.png);
	background-repeat: no-repeat;
	background-size: cover;

	box-sizing: border-box;
	/* 上下，左右 */
	padding: 2vw 6vw;
}

.wrapper .banner h3 {
	font-size: 4.2vw;
	/* 距离p标签高度 */
	margin-bottom: 1.2vw;
}

.wrapper .banner p {
	font-size: 3.4vw;
	color: #666;
	/* p，a标签间距 */
	margin-bottom: 2.4vw;
}

.wrapper .banner a {
	font-size: 3vw;
	color: #C79060;
	font-weight: 700;
}

/****************** 超级会员部分 ******************/
.wrapper .supermember {
	/*这里也设置容器宽度95%，不能用padding，因为背景色也会充满padding*/
	width: 95%;
	margin: 0 auto;
	height: 11.5vw;
	background-color: #FEEDC1;
	margin-top: 1.3vw;
	border-radius: 2px;
	color: #644F1B;

	display: flex;
	/* 分开靠左右两边 */
	justify-content: space-between;

	align-items: center;
}

.wrapper .supermember .left {
	display: flex;
	align-items: center;
	margin-left: 4vw;
	user-select: none;
}

.wrapper .supermember .left img {
	width: 6vw;
	height: 6vw;
	margin-right: 2vw;
}

.wrapper .supermember .left h3 {
	font-size: 4vw;
	margin-right: 2vw;
}

.wrapper .supermember .left p {
	font-size: 3vw;
}

.wrapper .supermember .right {
	font-size: 3vw;
	margin-right: 4vw;
	cursor: pointer;
}

/****************** 推荐商家部分 ******************/
.wrapper .recommend {
	width: 100%;
	height: 14vw;
	display: flex;
	justify-content: center;
	align-items: center;
}

.wrapper .recommend .recommend-line {
	width: 6vw;
	height: 0.2vw;
	background-color: #888;
}

.wrapper .recommend p {
	font-size: 4vw;
	margin: 0 4vw;
}

/****************** 推荐方式部分 ******************/
.wrapper .recommendtype {
	width: 100%;
	height: 5vw;
	margin-bottom: 5vw;

	display: flex;
	justify-content: space-around;
	align-items: center;
}

.wrapper .recommendtype li {
	font-size: 3.5vw;
	color: #555;
}

/****************** 推荐商家列表部分 ******************/
.wrapper .business {
	width: 100%;
	/* 高度不定 */
	padding-bottom: 14vw;
}

.wrapper .business li {
	width: 100%;
	box-sizing: border-box;
	padding: 2.5vw;
	user-select: none;
	/* 分割列表下边框 */
	border-bottom: solid 1px #DDD;
	display: flex;
}

.wrapper .business li img {
	width: 18vw;
	height: 18vw;
}

.wrapper .business li .business-info {
	width: 100%;
	/* 设置内边距 */
	box-sizing: border-box;
	padding-left: 3vw;
}

.wrapper .business li .business-info .business-info-h {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 2vw;
}

.wrapper .business li .business-info .business-info-h h3 {
	font-size: 4vw;
	color: #333;
}

.wrapper .business li .business-info .business-info-h .business-info-like {
	width: 1.6vw;
	height: 3.4vw;
	background-color: #666;
	color: #fff;
	font-size: 4vw;
	margin-right: 4vw;

	display: flex;
	justify-content: center;
	align-items: center;
}

.wrapper .business li .business-info .business-info-star {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 2vw;
	font-size: 3.1vw;
}

.wrapper .business li .business-info .business-info-star .business-info-star-left {
	display: flex;
	align-items: center;
}

.wrapper .business li .business-info .business-info-star .business-info-star-left .fa-star {
	color: #FEC80E;
	margin-right: 0.5vw;
}

.wrapper .business li .business-info .business-info-star .business-info-star-left p {
	color: #666;
	margin-left: 1vw;
}

.wrapper .business li .business-info .business-info-star .business-info-star-right {
	background-color: #0097FF;
	color: #fff;
	font-size: 2.4vw;
	border-radius: 2px;
	padding: 0 0.6vw;
}

.wrapper .business li .business-info .business-info-delivery {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 2vw;

	color: #666;
	font-size: 3.1vw;
}

.wrapper .business li .business-info .business-info-explain {
	display: flex;
	align-items: center;
	margin-bottom: 3vw;
}

.wrapper .business li .business-info .business-info-explain div {
	border: solid 1px #DDD;
	font-size: 2.8vw;
	color: #666;
	border-radius: 3px;
	padding: 0 0.1vw;
}

.wrapper .business li .business-info .business-info-promotion {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 1.8vw;
}

.wrapper .business li .business-info .business-info-promotion .business-info-promotion-left {
	display: flex;
	align-items: center;
}

.wrapper .business li .business-info .business-info-promotion .business-info-promotion-left .business-info-promotion-left-incon {
	width: 4vw;
	height: 4vw;
	background-color: #70BC46;
	border-radius: 3px;
	font-size: 3vw;
	color: #fff;

	display: flex;
	justify-content: center;
	align-items: center;
}

.wrapper .business li .business-info .business-info-promotion .business-info-promotion-left p {
	color: #666;
	font-size: 3vw;
	margin-left: 2vw;
}

.wrapper .business li .business-info .business-info-promotion .business-info-promotion-right {
	display: flex;
	align-items: center;
	font-size: 2.5vw;
	color: #999;
}

.wrapper .business li .business-info .business-info-promotion .business-info-promotion-right p {
	margin-right: 2vw;
}

/****************** 底部菜单部分 ******************/


</style>